package com.hmall.item.web;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.comstants.MqConstants;
import com.hmall.common.dto.PageDTO;

import com.hmall.item.pojo.Item;

import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Date;

@Slf4j
@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IItemService itemService;
    @GetMapping("/list")
    public PageDTO<Item> queryItemByPage(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {
        // 分页查询
        Page<Item> result = itemService.page(new Page<>(page, size));
        // 封装并返回
        return new PageDTO<>(result.getTotal(), result.getRecords());
    }
    @GetMapping("/{id}")
    public Item FindById(@PathVariable Long id) {
        log.info("根据id查找，{}",id);
        return itemService.FindById(id);
    }
    @PostMapping
    public void Insert(@RequestBody Item item) {
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        item.setStatus(2);
        log.info("添加商品，{}",item);
        itemService.insert(item);
        rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.HMALL_INSERT_KEY,item.getId());

    }
    @PutMapping("/status/{id}/{status}")
    public void OnAndOff(@PathVariable Long id,@PathVariable Integer status) {
        log.info("上下架，{}，{}",id,status);
        itemService.OnAndOff(id,status);

    }
    @PutMapping
    public void Update(@RequestBody Item item) {
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        log.info("更改商品，{}",item);
        itemService.updateById(item);
        rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE, MqConstants.HMALL_INSERT_KEY, item.getId());

    }
    @DeleteMapping("{id}")
    public void DeleteById(@PathVariable Long id) {
        log.info("删除商品，{}",id);
        itemService.DeleteById(id);
        rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE, MqConstants.HMALL_DELETE_KEY, id);

    }



}
